# encoding: utf-8
import pathlib

from automatic.file.FolderCompareListener import FolderCompareListener
from automatic.file.FolderCompareResultType import FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE, \
    FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY


class FolderCompareLinuxGenerator(FolderCompareListener):

    file_object = None

    def __init__(self, output_path, new_dir, old_dir):
        self.new_dir = new_dir.replace("\\", "/")
        self.old_dir = old_dir.replace("\\", "/")
        self.output_path = output_path.replace("\\", "/")

    def begin(self):
        try:
            # open 需要加参数newline, 不然即使print函数加了\n也会自动转换为0D0A, 导致linux执行不了.
            self.file_object = open(self.output_path, "w", encoding="utf-8", newline="\n")
            print("new_root_dir=\"%s\"" % self.new_dir, file=self.file_object)
            print("old_root_dir=\"%s\"" % self.old_dir, file=self.file_object)
        except OSError as e:
            print(str(e))

    def process(self, result_type, new_root_dir, new_relative_dir, old_root_dir, old_relative_dir, file_name):

        new_sub_path = (new_relative_dir+"/"+file_name)if len(new_relative_dir) else file_name
        old_sub_path = (old_relative_dir + "/" + file_name) if len(old_relative_dir) else file_name

        new_sub_path = new_sub_path.replace("\\", "/")
        old_sub_path = old_sub_path.replace("\\", "/")

        if result_type == FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE:
            print("cp -f \"${new_root_dir}%s\" \"${old_root_dir}%s\"" % (
                new_sub_path, old_sub_path), file=self.file_object)
        elif result_type == FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY:
            new_path = pathlib.Path(new_root_dir + new_sub_path)
            if new_path.is_dir():
                print("cp -fR \"${new_root_dir}%s/\" \"${old_root_dir}%s\"" % (
                    new_sub_path, old_sub_path), file=self.file_object)
            else:
                print("cp -f \"${new_root_dir}%s\" \"${old_root_dir}%s\"" % (
                    new_sub_path, old_sub_path), file=self.file_object)
        else:
            print("rm -fr \"${old_root_dir}%s\"" % old_sub_path, file=self.file_object)